package com.xbn.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @author XBN
 * @date 2020/10/14 11:17
 * @email 78742541@qq.com
 */
public class ScatteringAndGatheringTest
{
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        //绑定端口到socket并启动
        serverSocketChannel.socket().bind(inetSocketAddress);
        //创建buffer数组
        ByteBuffer[] byteBuffers=new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1]=ByteBuffer.allocate(3);
        //监听等待客户端连接(telnet),获取一个SocketChannel
        SocketChannel socketChannel = serverSocketChannel.accept();
        int messageLen=8;//假定最多只能接收8个字符
        //循环读取
        while (true)
        {
            int byteRead=0;
            while (byteRead<messageLen)
            {//往缓冲区数组中放入
                long l = socketChannel.read(byteBuffers);
                byteRead+=l;//累计读取的字节数
                System.out.println("当前读取到的字节数为"+byteRead);
                //使用流打印，看看当前的buffer的position和limit
                Arrays.asList(byteBuffers).stream().map(byteBuffer -> "position="+byteBuffer.position()
                +",limit="+byteBuffer.limit()).forEach(System.out::println);
            }
            //将所有的buffer进行反转
            Arrays.asList(byteBuffers).forEach(byteBuffer -> byteBuffer.flip());
            //将数据读出，显示到我们的客户端
            long byteWrite=0;
            while (byteWrite<messageLen)
            {
                long l = socketChannel.write(byteBuffers);
                byteWrite+=l;
            }
            //将所有的buffer进行clear
            Arrays.asList(byteBuffers).stream().forEach(byteBuffer -> byteBuffer.clear());
            System.out.println("byteRead="+byteRead+",byteWrite="+byteWrite+"messageLen"
            +messageLen);
        }
    }
}
